<template>
  <div class="word">
    <div class="left-panel">
      <!-- 此div用来加载PageOffice客户端控件，其中div的高宽及位置就决定了控件的大小及位置 -->
      <div style="width:auto; height:100%;" v-html="poHtmlCode"></div>
    </div>
    <div class="right-panel">
      <h3>合同信息</h3>
      <el-form ref="form" label-width="150px" :model="formData">
        <el-form-item label="采购人：" prop="purchaser">
          <el-select v-model="formData.purchaser" placeholder="请选择采购人">
            <el-option v-for="purchaser in formData.purchasers" :key="purchaser" :label="purchaser" :value="purchaser">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商：" prop="supplier">
          <el-select v-model="formData.supplier" placeholder="请选择供应商">
            <!-- 下拉选项 -->
            <el-option v-for="supplier in formData.suppliers" :key="supplier" :label="supplier" :value="supplier">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购方企业：" prop="buyer_company">
          <el-select v-model="formData.buyer_company" placeholder="请选择采购方企业">
            <!-- 下拉选项 -->
            <el-option v-for="buyer_company in formData.buyer_companys" :key="buyer_company" :label="buyer_company"
              :value="buyer_company">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目编号：" prop="project_number">
          <el-input v-model="formData.project_number" placeholder="请输入项目编号"></el-input>
        </el-form-item>

        <hr>
        <div style="display: flex;padding: 10px 40px;">
          <el-button type="primary" :disabled="!formData.selectedGood" class="add-button"
            @click="addGoods(formData.selectedGood)">添加到清单</el-button>
          <el-select v-model="formData.selectedGood" placeholder="请选择货品" style="margin-left: 10px;">
            <el-option v-for="good in goodsList" :key="good.id" :label="getGoodLabel(good)" :value="good.id">
            </el-option>
          </el-select>
        </div>
      </el-form>
      <h5>采购货品清单:</h5>
      <!-- 采购货品清单表格 -->
      <el-table :data="goods">
        <el-table-column prop="name" label="货物品名"></el-table-column>
        <!-- <el-table-column prop="specification" label="规格"></el-table-column> -->
        <el-table-column prop="model" label="型号"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="unit_price" label="单价"></el-table-column>
        <!-- <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="deleteGood(scope.$index)">删除</el-button>
          </template>
</el-table-column> -->
      </el-table>
      <div>合同总价：{{ total_rmb }} RMB</div>
      <div class="footer">
        <el-button @click="resetForm()">重置内容</el-button>
        <el-button type="primary" @click="submit()">确认填写</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      poHtmlCode: '',
      total_rmb: 0,//合同总价
      formData: {
        purchaser: "", // 默认值为空字符串
        purchasers: ["刘培强", "图恒宇", "周喆直", "张鹏", "马兆"],
        supplier: "",
        suppliers: ["国盾量子", "科大国创"],
        buyer_company: "",
        buyer_companys: ["卓正软件", "卓正PageOffice"],
        project_number: "",
        selectedGood: "", // 选中的货品
        // selectedGoods:["量子计算机550A,入门型,100RMB/台", "量子计算机550C,旗舰型,200RMB/台", "量子计算机550W,发烧型,300RMB/台"], // 选中的货品
      },
      goods: [],
      goodsList: [ // 货品列表示例数据
        { id: 1, name: '量子计算机', specification: '550A', model: '入门型', unit: '台', quantity: 1, unit_price: '100RMB' },
        { id: 2, name: '量子计算机', specification: '550C', model: '旗舰型', unit: '台', quantity: 1, unit_price: '200RMB' },
        { id: 3, name: '量子计算机', specification: '550W', model: '发烧型', unit: '台', quantity: 1, unit_price: '300RMB' },
        // ...其他货品数据
      ]
    };
  },
  created: function () {
    // 请求后端打开文件
    this.openFile().then(response => {
      this.poHtmlCode = response;
    });
  },
  methods: {
    addGoods(selectedItem) {
      // 将选中的货品添加到货品清单中
      let filterGoods = this.goodsList.filter(item => item.id === selectedItem);
      this.goods = [...this.goods, ...filterGoods];
      //计算合同总价
      this.total_rmb = this.goods.reduce((total, item) => {
        //unit_price的格式总是'xxxRMB'，其中xxx是数字,只想要数字相加，就要用正则去掉非数字字符  
        const priceWithoutCurrency = item.unit_price.replace(/[^\d.]/g, ''); // 移除非数字字符  
        const price = parseFloat(priceWithoutCurrency); // 转换为浮点数  
        return total + price;
      }, 0);
    },
    getGoodLabel(good) {
      return `${good.name}${good.specification}` + '，' + `${good.model}` + '，' + `${good.unit_price}` + '/台';
    },
    deleteGood(index) {
      this.goods = this.goods.filter((_, i) => i !== index)
    },
    resetForm() {
      // 重置表单数据，但不改变原始数据，想要正确清除表单，每个form表单元素上必要要有prop属性，值和v-model的一致
      this.$refs.form.resetFields();
    },
    submit() {
      //将form表单中的值回填到word中
      pageofficectrl.word.SetValueToDataRegion('PO_Buyer', this.formData.purchaser);
      pageofficectrl.word.SetValueToDataRegion('PO_Supplier', this.formData.supplier);
      pageofficectrl.word.SetValueToDataRegion('PO_company', this.formData.buyer_company);
      pageofficectrl.word.SetValueToDataRegion('PO_code', this.formData.project_number);
      pageofficectrl.word.SetValueToDataRegion('PO_rmb', this.total_rmb.toString());

      //获取goods中货品的数量
      let goodsCount = this.goods.length;
      //根据goods中货品的数量给表格新增行，模板中默认只有一个表头
      for (let row = 1; row <= goodsCount; row++) {
        pageofficectrl.word.SelectTableCell("PO_table", 1, row, 6);//选中单元格。在(2,6)这个坐标所在的单元格下方新增行
        pageofficectrl.word.AppendTableRow();//在当前SelectTableCell方法选中的单元格的下方增加新的一行
      }

      //根据单元格坐标循环给table赋值
      for (let i = 1; i <= goodsCount; i++) { //行
        for (let j = 1; j <= 6; j++) { //列
          pageofficectrl.word.SelectTableCell("PO_table", 1, i + 1, j);//选中单元格。
          let good = this.goods[i - 1];//good：代表当前货品对象
          switch (j) {
            case 1:
              pageofficectrl.word.SetTextToSelection(`${good.name}`);//给选中的内容赋值
              break;
            case 2:
              pageofficectrl.word.SetTextToSelection(`${good.specification}`);
              break;
            case 3:
              pageofficectrl.word.SetTextToSelection(`${good.model}`);
              break;
            case 4:
              pageofficectrl.word.SetTextToSelection(`${good.unit}`);
              break;
            case 5:
              pageofficectrl.word.SetTextToSelection(`${good.quantity}`);
              break;
            case 6:
              pageofficectrl.word.SetTextToSelection(`${good.unit_price}`);
              break;
          }
        }
      }
    },
    Save() {
      pageofficectrl.SaveFilePage = "/FormToDataRegions/save";
      //在这里写您保存前的代码
      pageofficectrl.WebSave();
      //在这里写您保存后的代码，比如判断保存结果pageofficectrl.CustomSaveResult
    },
    OnPageOfficeCtrlInit() {
      // PageOffice的初始化事件回调函数，您可以在这里添加自定义按钮
      pageofficectrl.AddCustomToolButton("保存", "Save", 1);
    },
    openFile() {
      return request({
        url: '/FormToDataRegions/Word',
        method: 'get',
      })
    }
  },
  mounted: function () {
    //将当前页面methods中定义的函数挂载到PageOffice控件，例如控件触发的事件、自定义按钮触发的函数。
    window.POPageMounted = this;//此行必须
  }
}

</script>

<style scoped>
/* 设置整个页面的样式 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

/* 设置Flex容器 */
.word {
  display: flex;
  /* 启用Flex布局 */
  height: 100vh;
  /* 占满整个视口高度 */
  width: 100%;
  /* 占满整个视口宽度（或省略，因为默认就是100%） */
}

/* 设置左侧面板的样式 */
.left-panel {
  flex: 0 0 60%;
  /* 等宽分配 */
  /* 可以添加其他样式 */
}

/* 设置右侧面板的样式 */
.right-panel {
  flex: 0 0 40%;
  /* 等宽分配 */
  background-color: #f4f4f4;
  padding: 10px;
  /* 设置背景色 */
  /* 可以添加其他样式 */
}

.el-select,
.el-input {
  width: 300px;
}

.el-table {
  width: 500px;
}

/* 确保选择货品并添加的文本不换行 */
.el-form-item__label {
  white-space: nowrap;
}

.add-button {
  margin-bottom: 15px;
}

.footer {
  margin-top: 10px;
  text-align: center;
}
</style>
